package de.dailab.prefgen;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import de.dailab.prefgen.INameMapping.TYPE;

import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;

public class TextLeaf implements ILeafFactory {

	@Override
	public boolean shouldGenerate(Class type) {
		return String.class.isAssignableFrom(type);
	}

	@Override
	public Preference generate(Object superObject, Method callingMethod,
			PreferenceActivity context, INameMapping nameMapping) {

		EditTextPreference edit = new EditTextPreference(context);
		edit.setDialogTitle(nameMapping.toHumanReadable(callingMethod,
				superObject, TYPE.TITLE));
		// TODO need Canonical Name
		edit.setKey(nameMapping.toHumanReadable(callingMethod, superObject,
				TYPE.KEY));
		edit.setTitle(nameMapping.toHumanReadable(callingMethod, superObject,
				TYPE.TITLE));
		edit.setSummary(nameMapping.toHumanReadable(callingMethod, superObject,
				TYPE.DESCRIPTION));
		edit.getEditText().setSingleLine(true);
		edit.setPersistent(false);
		edit.setOnPreferenceChangeListener(new OnLeafPrefernceChangedListener(
				superObject, callingMethod, nameMapping));

		try {

			Object obj = callingMethod.invoke(superObject, null);

			edit.setText(obj != null ? obj.toString() : null);

			return edit;

		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

}
